package org.sys.transporttrainsys.controller;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.sys.transporttrainsys.dto.LearningStatistics;
import org.sys.transporttrainsys.entity.StudentLearningStatus;
import org.sys.transporttrainsys.service.StudentLearningStatusService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse; // 使用 javax 版本
import java.io.ByteArrayOutputStream;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:5173") // 允许来自特定来源的跨域请求
@RequestMapping("/api/student-learning-status") // 基础请求路径
public class StudentLearningStatusController {

    private final StudentLearningStatusService service;

    public StudentLearningStatusController(StudentLearningStatusService service) {
        this.service = service;
    }

    // 获取所有学员学习情况
    @GetMapping
    public List<StudentLearningStatus> getAllLearningStatuses() {
        return service.getAllLearningStatuses();
    }

    // 根据学生 ID 获取学习情况
    @GetMapping("/student/{studentId}")
    public List<StudentLearningStatus> getByStudentId(@PathVariable Long studentId) {
        return service.getByStudentId(studentId);
    }

    // 根据培训计划 ID 获取学习情况
    @GetMapping("/training-plan/{trainingPlanId}")
    public List<StudentLearningStatus> getByTrainingPlanId(@PathVariable Long trainingPlanId) {
        return service.getByTrainingPlanId(trainingPlanId);
    }

    // 获取统计数据
    @GetMapping("/stats")
    public List<LearningStatistics> getStatistics() {
        return service.getStatistics();
    }

    // 下载学习情况报表（如果需要，可以添加实现）
    // 导出学习情况报表
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportLearningStatuses() {
        List<StudentLearningStatus> statuses = service.getAllLearningStatuses();

        // 创建 Excel 文档
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("学员学习情况");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("学员姓名");
        headerRow.createCell(2).setCellValue("培训计划");
        headerRow.createCell(3).setCellValue("学习进度");
        headerRow.createCell(4).setCellValue("最后学习时间");
        headerRow.createCell(5).setCellValue("学习状态");

        // 填充数据
        int rowNum = 1;
        for (StudentLearningStatus status : statuses) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(status.getId());
            row.createCell(1).setCellValue(status.getStudent() != null ? status.getStudent().getName() : "未知学员");
            row.createCell(2).setCellValue(status.getTrainingPlan() != null ? status.getTrainingPlan().getName() : "未知培训计划");
            row.createCell(3).setCellValue(status.getProgress());
            row.createCell(4).setCellValue(status.getLastLearnTime() != null ? status.getLastLearnTime().toString() : "");
            row.createCell(5).setCellValue(status.getStatus() != null ? status.getStatus().getDisplayName() : "未知状态");
        }

        // 将工作簿写入字节数组输出流
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            workbook.write(outputStream);
            workbook.close();

            byte[] bytes = outputStream.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=learning_statuses.xlsx");

            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}